package top.tangyh.lamp.qc.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import top.tangyh.basic.base.R;
import top.tangyh.lamp.care.service.BCarePgVteService;
import top.tangyh.lamp.care.service.BPatientService;
import top.tangyh.lamp.care.service.BPgRecordService;
import top.tangyh.lamp.care.service.BPipeUseRecordService;
import top.tangyh.lamp.care.vo.query.QcQueryPageVO;
import top.tangyh.lamp.care.vo.result.*;
import top.tangyh.lamp.care.vo.save.PgRecordVo;
import top.tangyh.lamp.qc.vo.query.QcFormulaQuery;
import top.tangyh.lamp.qc.vo.result.QcRateResult;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

/**
 * @author: zqb
 * @date: 2024/10/17 13:23
 */
@Slf4j
@RequiredArgsConstructor
@Validated
@RestController
@RequestMapping("/qc")
@Tag(name = "系统：质控")
public class QualityControlController {

    private final BPipeUseRecordService bPipeUseRecordService;

    private final BPgRecordService bPgRecordService;

    private final BPatientService bPatientService;

    private final BCarePgVteService bCarePgVteService;


    @Operation(summary = "icu非计划插管拔管率-计算")
    @PostMapping("/unplannedIntubationExtubationRate")
    public R<QcRateResult> UnplannedIntubationExtubationRate(@RequestBody QcFormulaQuery qcFormulaQuery) {
        QcRateResult qcRateResult = new QcRateResult();

        //分子：拔管是非计划拔管的拔管记录数量
        int molecular = bPipeUseRecordService.countOfUnplannedExtubation(qcFormulaQuery.getStartTime(), qcFormulaQuery.getEndTime());
        qcRateResult.setMolecular(molecular);

        //分母：同期管道插管总数量
        int denominator = bPipeUseRecordService.countOfUnplannedExtubationAll(qcFormulaQuery.getStartTime(), qcFormulaQuery.getEndTime());
        qcRateResult.setDenominator(denominator);
        //icu非计划插管拔管率 （小数点保留两位 四舍五入）
        //计算非计划插管拔管率
        if (denominator != 0) {
            double rate = (double) molecular / denominator * 100;
            BigDecimal result = new BigDecimal(rate).setScale(2, RoundingMode.HALF_UP); //四舍五入保留两位小数
            qcRateResult.setResult(result);
            return R.success(qcRateResult);
        } else {
            log.error("icu非计划插管拔管率 分母为0，无法计算率");
            return R.fail("icu非计划插管拔管率 分母为0，无法计算结果");
        }
    }


    @Operation(summary = "icu非计划插管拔管率-分页查询")
    @PostMapping("/page")
    public R<IPage<BPipeUseRecordResultVO>> page(@RequestBody QcQueryPageVO dataQuery) {

        return R.success(bPipeUseRecordService.pageOfPipeUseRecord(dataQuery));
    }


    @Operation(summary = "icu非计划插管拔管率-前6个月按月统计")
    @PostMapping("/pipeUserRecordStatisticsOfSixMonth")
    public R<List<StatisticsByMonth>> pipeUserRecordStatisticsOfSixMonth(
            @Parameter(description = "开始时间")
            @RequestParam String startTime) {
        List<StatisticsByMonth> list = bPipeUseRecordService.pipeUserRecordStatisticsOfSixMonth(startTime);
        return R.success(list);
    }


    //------------------------------------------------镇痛评估率>

    @Operation(summary = "镇痛评估率-计算")
    @PostMapping("/painRate")
    public R<QcRateResult> PainRate(@RequestBody QcFormulaQuery qcFormulaQuery) {
        QcRateResult qcRateResult = new QcRateResult();

        //分子：拔管是非计划拔管的拔管记录数量
        int molecular = bPgRecordService.countOfPainCalmPatient(qcFormulaQuery.getStartTime(), qcFormulaQuery.getEndTime(), "疼痛");
        qcRateResult.setMolecular(molecular);

        //分母：同期管道插管总数量
        int denominator = bPatientService.countOfAllIcuPatient(qcFormulaQuery.getStartTime(), qcFormulaQuery.getEndTime());
        qcRateResult.setDenominator(denominator);
        //计算镇痛评估率
        if (denominator != 0) {
            double rate = (double) molecular / denominator * 100;
            //四舍五入保留两位小数
            BigDecimal result = new BigDecimal(rate).setScale(2, RoundingMode.HALF_UP);

            qcRateResult.setResult(result);
            return R.success(qcRateResult);
        } else {
            log.error("镇痛评估率 分母为0，无法计算率");
            return R.fail("镇痛评估率 分母为0，无法计算结果");
        }
    }


    @Operation(summary = "镇痛评估率-分页查询(查询所有镇痛评估记录)")
    @PostMapping("/pain/page")
    public R<IPage<BPgRecordResultVO>> pageOfPgRecord(@RequestBody QcQueryPageVO dataQuery) {

        return R.success(bPgRecordService.pageOfPgRecord(dataQuery, "疼痛"));
    }


    @Operation(summary = "镇痛评估率-前6个月按月统计")
    @PostMapping("/painStatisticsOfSixMonth")
    public R<List<StatisticsByMonth>> painRecordStatisticsOfSixMonth(
            @Parameter(description = "开始时间")
            @RequestParam String startTime) {
        List<StatisticsByMonth> list = bPgRecordService.painnCalmStatisticsOfSixMonth(startTime, "疼痛");
        return R.success(list);
    }


    //------------------------------------------------镇静评估率>


    @Operation(summary = "镇静评估率-计算")
    @PostMapping("/calmRate")
    public R<QcRateResult> calmRate(@RequestBody QcFormulaQuery qcFormulaQuery) {
        QcRateResult qcRateResult = new QcRateResult();

        //分子：拔管是非计划拔管的拔管记录数量
        int molecular = bPgRecordService.countOfPainCalmPatient(qcFormulaQuery.getStartTime(), qcFormulaQuery.getEndTime(), "镇静评分");
        qcRateResult.setMolecular(molecular);

        //分母：同期管道插管总数量
        int denominator = bPatientService.countOfAllIcuPatient(qcFormulaQuery.getStartTime(), qcFormulaQuery.getEndTime());
        qcRateResult.setDenominator(denominator);
        //计算镇痛评估率
        if (denominator != 0) {
            double rate = (double) molecular / denominator * 100;
            BigDecimal result = new BigDecimal(rate).setScale(2, RoundingMode.HALF_UP); //四舍五入保留两位小数
            qcRateResult.setResult(result);
            return R.success(qcRateResult);
        } else {
            log.error("镇静评估率 分母为0，无法计算率");
            return R.fail("镇静评估率 分母为0，无法计算结果");
        }
    }


    @Operation(summary = "镇静评估率-分页查询(查询所有镇痛评估记录)")
    @PostMapping("/calm/page")
    public R<IPage<BPgRecordResultVO>> pageOfCalmPgRecord(@RequestBody QcQueryPageVO dataQuery) {

        return R.success(bPgRecordService.pageOfPgRecord(dataQuery, "镇静评分"));
    }


    @Operation(summary = "镇静评估率-前6个月按月统计")
    @PostMapping("/calmStatisticsOfSixMonth")
    public R<List<StatisticsByMonth>> calmRecordStatisticsOfSixMonth(
            @Parameter(description = "开始时间")
            @RequestParam String startTime) {
        List<StatisticsByMonth> list = bPgRecordService.painnCalmStatisticsOfSixMonth(startTime, "镇静评分");
        return R.success(list);
    }


    //------------------------------------------------急性生理与慢性健康评分 APACHEⅡ >
    @Operation(summary = "APACHEⅡ-计算")
    @PostMapping("/apacheii/rate")
    public R<QcRateResult> APACHEⅡRate(@RequestBody QcFormulaQuery qcFormulaQuery) {
        QcRateResult qcRateResult = new QcRateResult();

        //分子：入ICU后首次APACHEⅡ评分≥15分的患者人数
        int molecular = bCarePgVteService.getFirstApacheiiPatients(qcFormulaQuery.getStartTime(), qcFormulaQuery.getEndTime()).size();
        qcRateResult.setMolecular(molecular);

        //分母：同期ICU收治患者总数
        int denominator = bPatientService.countOfAllIcuPatient(qcFormulaQuery.getStartTime(), qcFormulaQuery.getEndTime());
        qcRateResult.setDenominator(denominator);
        //计算  患者收治率
        if (denominator != 0) {
            double rate = (double) molecular / denominator * 100;
            //四舍五入保留两位小数
            BigDecimal result = new BigDecimal(rate).setScale(2, RoundingMode.HALF_UP);
            qcRateResult.setResult(result);
            return R.success(qcRateResult);
        } else {
            log.error("急性生理与慢性健康评分 APACHEⅡ患者收治率 分母为0，无法计算率");
            return R.fail("急性生理与慢性健康评分 APACHEⅡ患者收治率  分母为0，无法计算结果");
        }
    }

    @Operation(summary = "APACHEⅡ-分页查询")
    @PostMapping("/apacheii/page")
    public R<IPage<BCarePgVteResultVO>> pageOfApacheII(@RequestBody QcQueryPageVO dataQuery) {

        return R.success(bCarePgVteService.getPagedApacheIIResult(dataQuery.getStartTime(), dataQuery.getEndTime(), dataQuery.getPage(), dataQuery.getSize()));
    }


    @Operation(summary = "APACHEⅡ-柱状图统计")
    @PostMapping("/apcheii/first/pfStatistic")
    public R<List<Apache2Statstic>> apcheIIFisrtPfStatistics(@RequestBody QcFormulaQuery qcFormulaQuery) {
        List<Apache2Statstic> list = bCarePgVteService.selectApacheIIFirstStatistics(qcFormulaQuery.getStartTime(), qcFormulaQuery.getEndTime());
        return R.success(list);
    }
}
